package com.dream.app.controller;

import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.dream.app.cache.AppCodeCache;
import com.dream.app.service.OrgService;
import com.dream.base.controller.BaseController;
import com.dream.master.service.ProductCategoryService;
import com.dream.master.service.ProductService;
import com.dream.master.service.ShopService;
import com.dream.model.master.Product;
import com.dream.model.master.ProductCategory;
import com.dream.model.order.OnlineOrder;
import com.dream.model.order.OnlineOrder.OrderStatus;
import com.dream.model.order.OrderCustomer;
import com.dream.model.order.OrderCustomerProduct;
import com.dream.order.service.OrderService;
import com.dream.utils.annotation.AccessLog;
import com.dream.utils.annotation.SkipAuthority;
import com.dream.utils.hibernate.PagingVO;
import com.dream.utils.log.DreamLogUtils;
import com.dream.vo.app.AppCodeConstants;
import com.dream.vo.base.FirstGroup;
import com.dream.vo.base.MvcValidtorResult;
import com.dream.vo.base.ResultType;
import com.dream.vo.base.SecondGroup;
import com.dream.vo.order.CustomerProductVO;
import com.dream.vo.order.CustomerVO;
import com.dream.vo.order.OrderQueryVO;
import com.dream.vo.order.OrderVO;
import com.google.common.collect.Maps;

/**
 * @copyright evan
 * @author evan
 * @Revision
 * @date 2013/9/29
 */
@Controller
@RequestMapping(value = "/order")
public class OrderController extends BaseController{
	
	
	@Autowired
	private AppCodeCache codeCache;
	
	@Autowired
	private OrgService orgService;
	
	@Autowired
	private OrderService orderService;
	
	@Autowired
	private ShopService shopService;
	
	@Autowired
	private ProductCategoryService productCategoryService;
	
	@Autowired
	private ProductService productService;
	
	@RequestMapping(value = "/list/init")
	@SkipAuthority
	public String stockListInit(Model modelMap, String loc) {
		
		modelMap.addAttribute("orderTypeList", codeCache.getByAppCodeName(AppCodeConstants.ORDER_TYPE));
		modelMap.addAttribute("orderStatusList", OrderStatus.getTypes());
		modelMap.addAttribute("firstOrgs",orgService.getFirstOrg());
		
		return loc;
		
	}
	
	@RequestMapping(value = "/list")
	@SkipAuthority
	public String orderList(Model modelMap,OrderQueryVO vo,PagingVO page) {
		
		modelMap.addAttribute("pageVO",orderService.query(vo, page, getUser()));
		return "order/data/order_list_data";
		
	}
	
	@RequestMapping(value = "/dispatch/list")
	@SkipAuthority
	public String dispatchOrderList(Model modelMap,OrderQueryVO vo,PagingVO page) {
		
		vo.setStatus(OrderStatus.order_submit.name());
		modelMap.addAttribute("pageVO",orderService.query(vo, page, getUser()));
		return "order/data/order_dispatch_list_data";
		
	}
	
	@RequestMapping(value = "/accept/list")
	@SkipAuthority
	public String acceptOrderList(Model modelMap,OrderQueryVO vo,PagingVO page) {
		
		vo.setStatus(OrderStatus.order_dispatch.name());
		vo.setShops(shopService.queryMyShopId(getUser()));
		if(vo.getShops().isEmpty()){
			vo.getShops().add("-1");
		}
		modelMap.addAttribute("pageVO",orderService.query(vo, page, getUser()));
		return "order/data/order_accept_list_data";
		
	}
	
	@RequestMapping(value = "/deal/list")
	@SkipAuthority
	public String dealOrderList(Model modelMap,OrderQueryVO vo,PagingVO page) {
		
		vo.setStatus(OrderStatus.order_accept.name());
		vo.setShops(shopService.queryMyShopId(getUser()));
		if(vo.getShops().isEmpty()){
			vo.getShops().add("-1");
		}
		modelMap.addAttribute("pageVO",orderService.query(vo, page, getUser()));
		return "order/data/order_deal_list_data";
		
	}
	
	@RequestMapping(value = "/submit/init")
	@SkipAuthority
	public String submitOrderInit(Model modelMap) {
		
		modelMap.addAttribute("customerTypeList", codeCache.getByAppCodeName(AppCodeConstants.CUSTOMER_TYPE));
		
		modelMap.addAttribute("orderTypeList", codeCache.getByAppCodeName(AppCodeConstants.ORDER_TYPE));
		modelMap.addAttribute("urgentLevelList", codeCache.getByAppCodeName(AppCodeConstants.ORDER_URGENT_TYPE));
		modelMap.addAttribute("mandatoryLevelList", codeCache.getByAppCodeName(AppCodeConstants.ORDER_MADATORY_TYPE));
		
		modelMap.addAttribute("firstOrgs",orgService.getFirstOrg());
		ProductCategory childrens = productCategoryService.getChildrens(null);
		modelMap.addAttribute("firstCats", childrens==null ? null : childrens.getChildren());
		
		return "order_update";
		
	}
	
	@ResponseBody
	@RequestMapping(value = "/customer/update")
	@AccessLog(module="order",content="订单用户更新")
	@SkipAuthority
	public Map<String,Object> orderCustomerUpdate(Model modelMap,@Validated({FirstGroup.class}) CustomerVO vo,BindingResult valResult) {
		
		Map<String,Object> result = Maps.newHashMap();
		MvcValidtorResult errors = populateErrors(valResult);
		
		if(valResult.hasErrors()){
			result.put(RESULT_TYPE, ResultType.INPUT.toInteger());
			result.put(RESULT_CONTENT, errors);
			
		}else{
			try{
				OrderCustomer updateCustomer = orderService.updateCustomer(vo, getUser());
				result.put(RESULT_TYPE,ResultType.SUCCESS.toInteger());
				result.put(RESULT_CONTENT, updateCustomer.getId());
			}catch(Exception ex){
					result.put(RESULT_TYPE, ResultType.EXCEPTION.toInteger());
					DreamLogUtils.error(this,"orderCustomerUpdate","order customer  occured exception", ex);
			}
		}
		return result;
	}
	
	@RequestMapping(value = "/customer/search")
	@SkipAuthority
	@ResponseBody
	public OrderCustomer searchCustomer(Model modelMap, String name,String mobile) {
		return orderService.searchCustomer(name, mobile);
		
	}
	
	@ResponseBody
	@RequestMapping(value = "/product/update")
	@AccessLog(module="order",content="订单用户产品更新")
	@SkipAuthority
	public Map<String,Object> orderProductUpdate(Model modelMap,@Validated({FirstGroup.class}) CustomerProductVO vo,BindingResult valResult) {
		
		Map<String,Object> result = Maps.newHashMap();
		MvcValidtorResult errors = populateErrors(valResult);
		
		Product p = productService.search(vo.getProductName(), Long.parseLong(vo.getSecondCat()));
		if(p == null){
			errors.getGlobalErrors().add("当前品牌不存在此机型!");
		}
		
		if(errors.hasErrors()){
			result.put(RESULT_TYPE, ResultType.INPUT.toInteger());
			result.put(RESULT_CONTENT, errors);
			
		}else{
			try{
					vo.setProductId(p.getId());
					OrderCustomerProduct product = orderService.updateCustomerProduct(vo, getUser());
					result.put(RESULT_CONTENT, product.getId());
					result.put(RESULT_TYPE,ResultType.SUCCESS.toInteger());
			}catch(Exception ex){
					result.put(RESULT_TYPE, ResultType.EXCEPTION.toInteger());
					DreamLogUtils.error(this,"orderCustomerUpdate","order customer  occured exception", ex);
			}
		}
		return result;
	}
	
	@ResponseBody
	@RequestMapping(value = "/feedback")
	@AccessLog(module="order",content="订单维修填单")
	@SkipAuthority
	public Map<String,Object> orderProductFeeback(Model modelMap,@Validated({SecondGroup.class})  OrderVO vo,BindingResult valResult) {
		
		vo.setStatus(OrderStatus.order_fixed);
		return updateOrder(vo, valResult);
	}
	
	@RequestMapping(value = "/product/search")
	@SkipAuthority
	@ResponseBody
	public OrderCustomerProduct searchProduct(Model modelMap, String productName,Long customerId) {
		return orderService.searchProduct(productName, customerId);
		
	}
	
	@ResponseBody
	@RequestMapping(value = "/update")
	@AccessLog(module="order",content="订单更新")
	@SkipAuthority
	public Map<String,Object> orderUpdate(Model modelMap,@Validated({FirstGroup.class}) OrderVO vo,BindingResult valResult) {
		
		vo.setStatus(OrderStatus.order_submit);
		return updateOrder(vo, valResult);
	}

	private Map<String, Object> updateOrder(OrderVO vo, BindingResult valResult) {
		Map<String,Object> result = Maps.newHashMap();
		MvcValidtorResult errors = populateErrors(valResult);
		
		if(valResult.hasErrors()){
			result.put(RESULT_TYPE, ResultType.INPUT.toInteger());
			result.put(RESULT_CONTENT, errors);
			
		}else{
			try{
				OnlineOrder order = orderService.updateCustomerOrder(vo, getUser());
				result.put(RESULT_TYPE,ResultType.SUCCESS.toInteger());
				result.put(RESULT_CONTENT, order.getId());
			}catch(Exception ex){
					result.put(RESULT_TYPE, ResultType.EXCEPTION.toInteger());
					DreamLogUtils.error(this,"orderUpdate","order  occured exception", ex);
			}
		}
		return result;
	}
	
	@ResponseBody
	@RequestMapping(value = "/dispatch/{id}/{shopId}")
	@AccessLog(module="order",content="分发订单")
	@SkipAuthority
	public  Map<String, Object> dispatchOrder(@PathVariable Long id, @PathVariable String shopId) {
		
		Map<String,Object> result = Maps.newHashMap();
		try {
			
			orderService.dispatchOrder(id, shopId, getUser());
			result.put(RESULT_TYPE, ResultType.SUCCESS.toInteger());
		} catch (Exception ex) {
			result.put(RESULT_TYPE,ResultType.ERROR.toInteger());
			DreamLogUtils.error(this, "dispatchOrder","dispatch order occured exception", ex);
		}
		return result;
	}
	
	@ResponseBody
	@RequestMapping(value = "/accept/{id}")
	@AccessLog(module="order",content="分发订单")
	@SkipAuthority
	public  Map<String, Object> acceptOrder(@PathVariable Long id) {
		
		Map<String,Object> result = Maps.newHashMap();
		try {
			
			orderService.acceptOrder(id, getUser());
			result.put(RESULT_TYPE, ResultType.SUCCESS.toInteger());
		} catch (Exception ex) {
			result.put(RESULT_TYPE,ResultType.ERROR.toInteger());
			DreamLogUtils.error(this, "dispatchOrder","dispatch order occured exception", ex);
		}
		return result;
	}
	
	@RequestMapping(value = "/detail/{id}")
	@SkipAuthority
	public String searchOrder(Model modelMap, @PathVariable  Long id) {
		
		OnlineOrder detail = orderService.getDetail(id);
		modelMap.addAttribute("order",detail);
		modelMap.addAttribute("customer",detail.getOrderProduct().getCustomer());
		modelMap.addAttribute("product",detail.getOrderProduct());
		ProductCategory childrens = productCategoryService.getChildrens(null);
		modelMap.addAttribute("firstCats", childrens==null ? null : childrens.getChildren());
		modelMap.addAttribute("mandatoryLevelList", codeCache.getByAppCodeName(AppCodeConstants.ORDER_MADATORY_TYPE));
		
		modelMap.addAttribute("serviceTypeList", codeCache.getByAppCodeName(AppCodeConstants.ORDER_SERVICE_TYPE));
		modelMap.addAttribute("satisfactionList", codeCache.getByAppCodeName(AppCodeConstants.ORDER_SATISTACTION_TYPE));
		modelMap.addAttribute("repairTypeList", codeCache.getByAppCodeName(AppCodeConstants.ORDER_REPAIR_TYPE));
		
		return "order_feedback";
		
	}
	
}
